Introduction

You previously recapped the steps for sorting and filtering data that has been retrieved using the @FetchRequest API. In this exercise, you’ll put that into practice for an iOS app.

Scenario

In the last exercise, you fetched the menu data to be displayed in the Little Lemon food ordering app. However, the app needs to have some additional functionality – users should customize how the menu appears so that it is easier to find specific items. To make this possible, you’ll apply sorting and filtering logic to the menu data.

Instructions

Use the same Xcode project you used in the previous exercises and follow the steps below to update the application logic with sorting and filtering of the database items.

Step 1: Sorting by name

Open the Menu view file and create a function that returns an array or sort descriptors for Dish objects.

The function now returns an array with one sort descriptor that will sort the Dish data by title in ascending order.

Tip: If you have difficulty completing any of the steps above please review the following materials of the course "Working with data in iOS":

Step 2: Using the function to modify the FetchedObjects result

Inside the FetchedObjects constructor call which is currently empty, set the sortDescriptors argument and pass it the result of the buildSortDescriptors function call.

You can run your project again, register, and you should see that the menu list order has changed. This is because the sort descriptors sort the list of Dishes before displaying it on the screen.

Tip: If you have difficulty completing any of the steps above please review the following materials of the course "Working with data in iOS":

Step 3: Adding a search field to filter the data

Follow the steps below to add a search field that you can later use to filter the menu list to search for a particular dish by title:

Step 4: Add a function that returns a predicate to filter the FetchedObjets results

Inside the Menu struct, create a new function called buildPredicate and make it return the NSPredicate .

Tip: If you have difficulty completing any of the steps above please review the following materials of the course "Working with data in iOS":

Step 5: Update the FetchedObjets element with the added function

Inside the FetchedObjects constructor call, add a predicate argument before the sortDescriptors , and pass the result of the buildPredicate function call to it.

Step 6: Run the project

Run the application and register. In the menu tab, you should observe a new text field right above the menu list. Try writing a part of the name of any dish, and you should see the list shrink to the items that match the part of their title with the search text.

Conclusion

By completing this exercise, you’ll have experience interacting with sort descriptors, filtering with predicates, and fetching request calls to the database.